/**
 * 
 */
package t4j.concurrency;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author sz
 *
 * create time：2013-3-4
 */
public class AttemptLocking {

	private ReentrantLock lock = new ReentrantLock();
	
	public void untimed(){
		boolean captured = lock.tryLock();
		
		try{
			System.out.println("tryLock:" + captured);
		}finally{
			if(captured)
				lock.unlock();
		}
	}
	
	public void timed(){
		boolean captured = false;
		
		try {
			captured = lock.tryLock(2, TimeUnit.SECONDS);//尝试获取锁，2秒后失败
		} catch (InterruptedException e) {
			throw new RuntimeException();
		}
		try{
			System.out.println("tryLock(2, TimeUnit.SECONDS):" + captured);
		}finally{
			if(captured)
				lock.unlock();
		}
	}
	
	public static void main(String[] args) {
		final AttemptLocking al  = new AttemptLocking();
		
		al.untimed();
		
		al.timed();
		
		new Thread(){
			{setDaemon(true);}
			public void run(){
				al.lock.lock();
				System.out.println("acquired");
				try {
					TimeUnit.SECONDS.sleep(1);
					al.lock.unlock();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
		
		int i = 0 ;
		while(i < 10000){			
			i++;	
		}
		
		Thread.yield();
	
		al.untimed();		
		
		al.timed();///因为上面的线程锁了，这个也尝试获取锁，等了n秒后还获取不到就失败

	}
}
